// var baseUrl="http://192.168.1.139:9888"
var baseUrl="https://dfhd.guwengkj.com"
const APPID="wx3d38ce1103a82225";
const SECRET='3c41ca428b4d0f43cfaef6f567a1cc06'
const request={
  request: function(options){
    let {api,data={},method="POST",header='',callback}=options
    var url=baseUrl+api
    if(api.includes("http")){
      url=api
    }
    //获取token 缓存
    var token= wx.getStorageSync('token')
    if(token)token="Bearer "+token
    if(!header){
      header={
        // 'content-type': 'application/x-www-form-urlencoded'
        'content-type': 'application/json'
      }
    }
    header["Authorization"]=token || 'Basic ZGV2OmRldjEyMw== '
    return new Promise((resolve,reject)=>{
      wx.request({
        url: url,
        data,
        method,
        header,
        success (res){
          // console.log(res);
          resolve(res.data)
        },
        fail(error){
          wx.showToast({
            title: error.errMsg,
            icon: 'error',
            duration: 2000
          })
          reject(error)
        },
        complete(res){
          // console.log(res);
          if(res.data.code == 401) { // token过期
            wx.showToast({
              title: res.data.message,
              icon: 'error',
              duration: 2000
            })
            wx.setStorageSync('token', '');//清空token
            wx.navigateTo({ // 跳转登录页
              url: '/pages/login/login',
            })
          }
        }
      })
    })
  }
}
module.exports = request